﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using SqlSugar;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics.Tracing;
using Yitter.IdGenerator;

namespace Admin.NET.Application;

/// <summary>
/// 备料表服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
[EventData]
public class stocklistService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<stocklist> _stocklistRep;
    private readonly ISqlSugarClient _sqlSugarClient;
    private readonly SqlSugarRepository<tickets> _ticketsRep;
    public stocklistService(SqlSugarRepository<stocklist> stocklistRep, ISqlSugarClient sqlSugarClient, SqlSugarRepository<tickets> ticketsRep)
    {
        _ticketsRep = ticketsRep;
        _stocklistRep = stocklistRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询备料表 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询备料表")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<stocklistOutput>> Page(PagestocklistInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _stocklistRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.oddnumber.Contains(input.Keyword) || u.stoker.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.oddnumber), u => u.oddnumber.Contains(input.oddnumber.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.stoker), u => u.stoker.Contains(input.stoker.Trim()))
            .WhereIF(input.workordernum != null, u => u.workordernum == input.workordernum)
            .WhereIF(input.preparationtimeRange?.Length == 2, u => u.preparationtime >= input.preparationtimeRange[0] && u.preparationtime <= input.preparationtimeRange[1])
            .LeftJoin<tickets>((u, workordernum) => u.workordernum == workordernum.Id)
            .Select((u, workordernum) => new stocklistOutput
            {
                Id = u.Id,
                oddnumber = u.oddnumber,
                workordernum = u.workordernum,
                workordernumFkDisplayName = $"{workordernum.encode}",
                states = u.states,
                stoker = u.stoker,
                preparationtime = u.preparationtime,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
            });
        return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取备料表详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取备料表详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<stocklist> Detail([FromQuery] QueryByIdstocklistInput input)
    {
        return await _stocklistRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加备料表 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加备料表")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddstocklistInput input)
    {
        var entity = input.Adapt<stocklist>();
        entity.oddnumber=YitIdHelper.NextId().ToString();
        return await _stocklistRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新备料表 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新备料表")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdatestocklistInput input)
    {
        var entity = input.Adapt<stocklist>();
        await _stocklistRep.AsUpdateable(entity)
        .IgnoreColumns(u => new {
            u.oddnumber,
        })
        .ExecuteCommandAsync();
    }


    /// <summary>
    /// 进行备料表 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("进行备料表")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeletestocklistInput input)
    {
       
        var entity = await _stocklistRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        entity.states = true;
        entity.stoker = entity.CreateUserName;
        entity.preparationtime = DateTime.Now;
        await _stocklistRep.AsUpdateable(entity)
      .IgnoreColumns(u => new {
          u.oddnumber,
      })
      .ExecuteCommandAsync();


        var tickets = await _ticketsRep.GetFirstAsync(u =>u.Id== entity.workordernum) ?? throw Oops.Oh(ErrorCodeEnum.D1002);

        tickets.ticketsstates = true;
        tickets.actualstarttime = DateTime.Now;
        await _ticketsRep.AsUpdateable(tickets)
    
     .ExecuteCommandAsync();

    }

    /// <summary>
    /// 批量删除备料表 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除备料表")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeletestocklistInput> input)
    {
        var exp = Expressionable.Create<stocklist>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _stocklistRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _stocklistRep.FakeDeleteAsync(list);   //假删除
        //return await _stocklistRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDatastocklistInput input)
    {
        var workordernumData = await _stocklistRep.Context.Queryable<tickets>()
            .InnerJoinIF<stocklist>(input.FromPage, (u, r) => u.Id == r.workordernum)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.encode}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "workordernum", workordernumData },
        };
    }
    
    /// <summary>
    /// 导出备料表记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出备料表记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PagestocklistInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportstocklistOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "备料表导出记录");
    }
    
    /// <summary>
    /// 下载备料表数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载备料表数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportstocklistOutput>(), "备料表导入模板", (_, info) =>
        {
            if (nameof(ExportstocklistOutput.workordernumFkDisplayName) == info.Name) return _stocklistRep.Context.Queryable<tickets>().Select(u => $"{u.encode}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入备料表记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入备料表记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportstocklistInput, stocklist>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 工单号
                    var workordernumLabelList = pageItems.Where(x => x.workordernumFkDisplayName != null).Select(x => x.workordernumFkDisplayName).Distinct().ToList();
                    if (workordernumLabelList.Any()) {
                        var workordernumLinkMap = _stocklistRep.Context.Queryable<tickets>().Where(u => workordernumLabelList.Contains($"{u.encode}")).ToList().ToDictionary(u => $"{u.encode}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.workordernum = workordernumLinkMap.GetValueOrDefault(e.workordernumFkDisplayName ?? "");
                            if (e.workordernum == null) e.Error = "工单号链接失败";
                        });
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        return true;
                    }).Adapt<List<stocklist>>();
                    
                    var storageable = _stocklistRep.Context.Storageable(rows)
                        .SplitError(it => it.Item.oddnumber?.Length > 32, "单号长度不能超过32个字符")
                        .SplitError(it => it.Item.stoker?.Length > 32, "备料人长度不能超过32个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
